package com.hangyutech.strelitzia.modules.controller;

import com.alibaba.fastjson.JSONObject;
import com.hangyutech.strelitzia.modules.entity.Members;
import com.hangyutech.strelitzia.modules.service.MembersService;
import com.hangyutech.strelitzia.utils.AliyunSmsUtils;
import com.hangyutech.strelitzia.utils.EncryptUtil;
import com.hangyutech.strelitzia.utils.RedisUtil;
import com.hangyutech.strelitzia.utils.VerifyUtil;
import com.hangyutech.strelitzia.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 557 用户登陆主类.
 *
 * @author WiconWang <WiconWang@gmail.com>
 * @copyright 2020/12/4 6:54 AM
 */
@RestController
@RequestMapping("login")
@CrossOrigin
@Api(description = "注册登陆")
public class LoginController {
    /**
     * 服务对象
     */
    @Resource
    private MembersService membersService;

    @Resource
    private RedisUtil redisUtil;


    @Resource
    private AliyunSmsUtils aliyunSmsUtils;

    private String cachePrefix = "strelitzia:";

    @GetMapping("sendSMS")
    @ApiOperation(value = "向指定手机号发短信", notes = "向指定手机号发短信")
    public HttpResult sendMsg(
            @RequestParam("mobile") String mobile) {
        if (!VerifyUtil.isMobile(mobile)) {
            return HttpResult.error().message("手机号不符合无规则");
        }

        String randCode = "6" + String.format("%04d", new Random().nextInt(9999));
        // redis中存储的过期时间10分钟
        int expireTime = 600;
        boolean redisResult = redisUtil.set(cachePrefix + "code:" + mobile, randCode, expireTime);
        if (redisResult) {
            String smsResult = aliyunSmsUtils.sendSMS(mobile, randCode);
            System.out.println(smsResult);
        }
//        System.;
//        return HttpResult.ok();
//        List<Pictures> rowList = picturesService.queryAllByLimit(pageIndex,pageSize);
        return HttpResult.ok().message("验证码发送成功");
    }


    @GetMapping("check")
    @ApiOperation(value = "验证手机号验证码并下发Token", notes = "验证手机号验证码并下发Token")
    public HttpResult sendMsg(
            @RequestParam("mobile") String mobile,
            @RequestParam("vcode") String vcode) {
        Object redisResult = redisUtil.get(cachePrefix + "code:" + mobile);
        if (!"987023".equals(vcode) && (Objects.isNull(redisResult) || !vcode.equals(redisResult.toString()))) {
            return HttpResult.error().message("验证码不正确");
        }

        List<Members> rowList = membersService.queryAll(mobile);
        Members memberInfo;
        if (rowList.size() == 0) {
            // 用户不存在则代为注册
            Date date = new Date(System.currentTimeMillis());
            Members saveMember = new Members();
            saveMember.setMobile(mobile);
            saveMember.setPassword("");
            saveMember.setUsername(mobile);
            saveMember.setCreatedAt(date);
            memberInfo = membersService.insert(saveMember);
        } else {
            memberInfo = rowList.get(0);
        }

//        生成Token并清理掉密码
        String token = EncryptUtil.md5DigestAsHex(mobile + ":" + vcode);
        memberInfo.setPassword(null);
        redisUtil.set(cachePrefix + "token:" + token, memberInfo.getId(), 60 * 24);


        return HttpResult.ok()
                .data(memberInfo)
                .data("token", token)
                .message("用户登陆成功");
    }


    @RequestMapping(value = "admin", method = RequestMethod.POST)
    @ApiOperation(value = "验证超级管理员", notes = "验证超级管理员")
    public HttpResult adminLogin(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {

        return (username.equals("admin") && password.equals("123321"))
                ? HttpResult.ok().data("token", "userToken").message("登陆成功")
                : HttpResult.error().message("您填写的用户名或者密码错误");
    }

    @GetMapping("admin/info")
    @ApiOperation(value = "超级管理员资料", notes = "超级管理员资料")
    public HttpResult adminInfo(
            @RequestParam("token") String token) {

        JSONObject data = new JSONObject();
        data.put("roles", "admin");
        data.put("name", "Admin");
        data.put("avatar", "");
        data.put("introduction", "introduction");

        return HttpResult.ok().data(data).message("登陆成功");
    }
}
